﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Fluffy.Library.FileSources;
using Fluffy.Library.Utils;

namespace Fluffy.FileMenuCommands
{
	internal class OpenCommandModel
	{
		private readonly List<string> _recentDocuments = new List<string>();

		public event Action RecentDocumentsListChanged;
		public event Action<IFile> OpenFileAction;

		public OpenCommandModel()
		{
			LoadRecentDocumentsList();
		}

		private static string RecentDocumentsListFilePath
		{
			get { return Path.Combine(PathUtils.AppDataPath, "RecentDocuments.xml"); }
		}

		public List<string> RecentDocuments
		{
			get { return _recentDocuments; }
		}

		private void LoadRecentDocumentsList()
		{
			string filePath = RecentDocumentsListFilePath;

			if (!File.Exists(filePath))
				return;

			XDocument document = XDocument.Load(filePath);
			
			_recentDocuments.Clear();
			_recentDocuments.AddRange(document.Root.Elements("Document").Select(x => x.Value));
		}

		private void SaveRecentDocumentsList()
		{
			XDocument document = new XDocument();
			document.Add(new XElement("RecentFiles"));

			_recentDocuments.ForEach(x => document.Root.Add(new XElement("Document", x)));

			string filePath = RecentDocumentsListFilePath;
			string fileDir = Path.GetDirectoryName(filePath);

			if (!Directory.Exists(fileDir))
				Directory.CreateDirectory(fileDir);

			document.Save(filePath);
		}

		public void OpenFile(string filePath)
		{
			_recentDocuments.RemoveAll(x => string.Equals(x, filePath, StringComparison.CurrentCultureIgnoreCase));
			_recentDocuments.Insert(0, filePath);

			if (_recentDocuments.Count > 20)
				_recentDocuments.RemoveRange(20, _recentDocuments.Count - 20);

			SaveRecentDocumentsList();

			if (OpenFileAction != null)
			{
				LocalFile file = new LocalFile();
				file.Load(filePath);

				OpenFileAction(file);
			}

			if (RecentDocumentsListChanged != null)
				RecentDocumentsListChanged();
		}

		public void OpenLink(string link)
		{
			// TODO: register in recent documents
//			_recentDocuments.RemoveAll(x => string.Equals(x, filePath, StringComparison.CurrentCultureIgnoreCase));
//			_recentDocuments.Insert(0, filePath);
//
//			if (_recentDocuments.Count > 20)
//				_recentDocuments.RemoveRange(20, _recentDocuments.Count - 20);
//
//			SaveRecentDocumentsList();

			if (OpenFileAction != null)
			{
				LinkFile file = new LinkFile(link);
				OpenFileAction(file);
			}

//			if (RecentDocumentsListChanged != null)
//				RecentDocumentsListChanged();
		}
	}
}
